package April._22.answer.work4;
import java.io.*;
public class Main {
    public static void main(String[] args) {
        // 创建Runnable子类对象表示下载任务
        DownloadRunnable downloadTask = new DownloadRunnable();
        //开启3个线程，执行下载任务
        new Thread(downloadTask).start();
        new Thread(downloadTask).start();
        new Thread(downloadTask).start();
    }
}

class DownloadRunnable implements Runnable {
    //待下载的100M资源
    private int remaining = 100;
    private static final Object LOCK = new Object();

    /**
     * 在子线程中执行的下载任务的实现代码
     */
    @Override
    public void run() {
        //模拟下载过程所需要的时间延迟
        while (remaining > 0) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //模拟成功下载资源
            synchronized (LOCK) {
                if (remaining > 0) {
                    // 模拟该线程下载了1M的资源
                    remaining--;
                    // 打印信息
                    System.out.println(Thread.currentThread().getName() + "下载了1M资源，还剩" + remaining
                            + "M资源待下载");
                    if (remaining == 0) {
                        System.out.println("下载完毕");
                        return;
                    }
                }
            }
        }
    }

}
